import { logger } from '../utils/logger';
import prisma from '../lib/prisma';
import axios from 'axios';
import { QuestionType } from '@prisma/client';
import { AIAssessmentResponse, AssessmentRequest, AssessmentHistory } from '../types/aiAssessment';

interface AssessmentResult {
  score: number;
  feedback: string;
  analysis: {
    keyPoints: string[];
    mistakes: string[];
    suggestions: string[];
  };
}

export class AIAssessmentService {
  private static readonly API_ENDPOINT = process.env.AI_ASSESSMENT_API_URL;
  private static readonly API_KEY = process.env.AI_ASSESSMENT_API_KEY;

  // AI批改主入口
  static async assessSubmission(submissionId: string): Promise<AssessmentResult> {
    try {
      // 获取提交的答案和相关信息
      const submission = await prisma.submission.findUnique({
        where: { id: submissionId },
        include: {
          question: {
            include: {
              scoringCriteria: true
            }
          }
        }
      });

      if (!submission) {
        throw new Error('提交记录不存在');
      }

      // 根据题目类型选择不同的批改策略
      let assessmentResult: AssessmentResult;
      switch (submission.question.type) {
        case QuestionType.MULTIPLE_CHOICE:
          assessmentResult = await this.assessMultipleChoice(submission);
          break;
        case QuestionType.OPEN_ENDED:
          assessmentResult = await this.assessOpenEnded(submission);
          break;
        default:
          throw new Error('不支持的题目类型');
      }

      // 更新数据库中的评分和反馈
      await prisma.submission.update({
        where: { id: submissionId },
        data: {
          score: assessmentResult.score,
          feedback: assessmentResult.feedback,
          aiAssessment: {
            create: {
              keyPoints: assessmentResult.analysis.keyPoints,
              mistakes: assessmentResult.analysis.mistakes,
              suggestions: assessmentResult.analysis.suggestions
            }
          }
        }
      });

      return assessmentResult;
    } catch (error) {
      logger.error('AI批改失败', { error, submissionId });
      throw error;
    }
  }

  // 批改选择题
  private static async assessMultipleChoice(submission: any): Promise<AssessmentResult> {
    const { answer, question } = submission;
    const isCorrect = answer === question.correctAnswer;
    const score = isCorrect ? question.scoringCriteria?.score || 100 : 0;

    return {
      score,
      feedback: isCorrect ? '回答正确' : `回答错误，正确答案是：${question.correctAnswer}`,
      analysis: {
        keyPoints: [question.explanation || '无解析'],
        mistakes: isCorrect ? [] : ['选择了错误的答案'],
        suggestions: isCorrect ? [] : ['请仔细阅读题目，理解题意']
      }
    };
  }

  // 批改主观题
  private static async assessOpenEnded(submission: any): Promise<AssessmentResult> {
    try {
      // 调用AI服务进行批改
      const response = await axios.post<AIAssessmentResponse>(
        this.API_ENDPOINT as string,
        {
          answer: submission.answer,
          question: submission.question.content,
          referenceAnswer: submission.question.correctAnswer,
          scoringCriteria: submission.question.scoringCriteria
        },
        {
          headers: {
            'Authorization': `Bearer ${this.API_KEY}`,
            'Content-Type': 'application/json'
          }
        }
      );

      const aiResult: AIAssessmentResponse = response.data;

      // 处理AI返回的结果
      return {
        score: aiResult.score,
        feedback: aiResult.feedback,
        analysis: {
          keyPoints: aiResult.keyPoints,
          mistakes: aiResult.mistakes,
          suggestions: aiResult.suggestions
        }
      };
    } catch (error) {
      logger.error('AI服务调用失败', { error, submissionId: submission.id });
      throw new Error('AI批改服务暂时不可用，请稍后再试');
    }
  }

  // 批量批改
  static async batchAssess(submissionIds: string[]): Promise<Record<string, AssessmentResult>> {
    try {
      const results: Record<string, AssessmentResult> = {};

      // 并发处理所有提交
      await Promise.all(
        submissionIds.map(async (id) => {
          try {
            results[id] = await this.assessSubmission(id);
          } catch (error) {
            logger.error('批量批改单个提交失败', { error, submissionId: id });
            results[id] = {
              score: 0,
              feedback: '批改失败',
              analysis: {
                keyPoints: [],
                mistakes: ['系统错误'],
                suggestions: ['请重新提交']
              }
            };
          }
        })
      );

      return results;
    } catch (error) {
      logger.error('批量批改失败', { error, submissionIds });
      throw error;
    }
  }

  // 重新评估
  static async reassessSubmission(submissionId: string, teacherFeedback?: string): Promise<AssessmentResult> {
    try {
      // 获取之前的评估结果
      const previousAssessment = await prisma.aiAssessment.findFirst({
        where: { submissionId }
      });

      // 进行新的评估
      const newAssessment = await this.assessSubmission(submissionId);

      // 如果有教师反馈，将其纳入考虑
      if (teacherFeedback) {
        newAssessment.analysis.suggestions.push(
          '教师反馈：' + teacherFeedback
        );
      }

      // 比较新旧评估结果，并记录差异
      if (previousAssessment) {
        await prisma.assessmentHistory.create({
          data: {
            submissionId,
            oldScore: previousAssessment.score,
            newScore: newAssessment.score,
            reason: teacherFeedback || '系统重新评估',
            changedBy: 'AI_SYSTEM'
          }
        });
      }

      return newAssessment;
    } catch (error) {
      logger.error('重新评估失败', { error, submissionId });
      throw error;
    }
  }
}
